<template>
  <div class="register-container">
    <el-card class="register-box">
      <h1 class="register-title">图书管理系统 - 注册</h1>
      <el-form
        ref="registerForm"
        :model="registerForm"
        :rules="registerRules"
        @submit.native.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            prefix-icon="el-icon-message"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            prefix-icon="el-icon-lock"
            placeholder="请再次输入密码"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            class="register-btn"
            :loading="loading"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>

      <div class="bottom-links">
        <el-button type="text" @click="goToLogin">
          已有账号？立即登录
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      loading: false,
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    async handleRegister() {
      try {
        await this.$refs.registerForm.validate();
        this.loading = true;

        const users = JSON.parse(localStorage.getItem("users")) || [];
        const userExists = users.some(u => u.username === this.registerForm.username);

        if (userExists) {
          this.$message.error('用户名已被注册');
          return;
        }

        users.push({
          username: this.registerForm.username,
          email: this.registerForm.email,
          password: this.registerForm.password
        });

        localStorage.setItem("users", JSON.stringify(users));
        this.$message.success('注册成功！正在跳转登录页...');
        setTimeout(() => {
          this.$router.push('/login');
        }, 1500);
      } catch (error) {
        console.error('验证失败:', error);
      } finally {
        this.loading = false;
      }
    },
    goToLogin() {
      this.$router.push('/login');
    }
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f4f4f4;
}

.register-box {
  width: 300px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 20px;
}

.bottom-links {
  text-align: center;
  margin-top: 20px;
}
</style>